<?php

namespace App\Models\Live;

use App\Model\Category;
use App\Models\Tag\Tag;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Anchor extends Model
{
    use LiveStream;
    public $guarded = [];
    public function followers()
    {
        return $this->belongsToMany('App\Model\Users', 'user_anchor', 'anchor_id', 'user_id');
    }

    public function tag()
    {
        $tag =  Tag::where('anchor_id', $this->id)->first();

        if ( ! $tag) $tag = new Tag(['name' => $this->name, 'type' => 'anchor', 'is_rec' => 0, 'id' => 0]);

        return $tag;
    }

    public function getIdAttribute()
    {
        return $this->attributes['id'];
    }

    public function getCateAttribute()
    {
        $cate = DB::table('live_categories')->where('cid', $this->category_id)->where('live_id', $this->live_id)->value('id');
        $cate = DB::table('cate_live_cate')->where('live_cid', $cate)->value('cid');

        return Category::find($cate);
    }

    public function getLiveAttribute()
    {
        return DB::table('lives')->where('id', $this->live_id)->first();
    }

    public function getHomePageAttribute()
    {
        $tag = Tag::where('anchor_id', $this->id)->first();

        if ( ! $tag) return route('anchor.preview', [$this->id]);

        return route('anchor.show', [$tag->id]);
    }

    public function scopeOfCate($query, $cate)
    {
        $live_cates = DB::table('cate_live_cate')->where('cid', $cate)->pluck('live_cid');
        $live_cates = LiveCategory::whereIn('id', $live_cates)->get();

        if ($live_cates->isEmpty()) return $query->where(DB::raw('0=1'));
        $query->where(function ($query) use($live_cates) {
            $live_cates->map(function ($cate) use($query) {
                return $query->orWhere(function ($query) use($cate) {
                    return $query->where('anchors.category_id', $cate->cid)->where('anchors.live_id', $cate->live_id);
                });
            });
            return $query;
        });
        return $query;
    }
}
